import axios from "axios";
import store from "@/store/index.ts";
import router from "@/router/index.ts";
import { ElMessage, ElMessageBox } from "element-plus";
import { showLoading, hideLoading } from "@/utils/myloading.ts";

let configBaseURL = "http://localhost:5000/ManageSystem/";
if (process.env.NODE_ENV === "production") {
  configBaseURL = "http://218.19.141.119:5000/ManageSystem/";
}

// axios instance
const Request = axios.create({
  baseURL: configBaseURL,
  // 最大请求时间，单位ms
  timeoutErrorMessage: "请求超时，请重试",
  timeout: 20000,
  headers: {
    "Content-Type": "application/json;charset=UTF-8"
  }
});
// http request 拦截器
Request.interceptors.request.use(
  config => {
    // add token to every http request if exists
    if (localStorage.getItem("token")) {
      config.headers.Authorization = `Bearer ${localStorage.getItem("token")}`;
      showLoading();
    }
    return config;
  },
  error => {
    // todo 请求token失效的时候，跳转登录
    return Promise.reject(error);
  }
);

// 添加响应拦截器
// http response 拦截器
Request.interceptors.response.use(
  response => {
    // 对响应数据做点什么
    if (
      typeof response.data == "string" &&
      (response.data as string).length < 50 &&
      (response.data as string).length > 0 &&
      (response.data as string).length != 19 //不输出日期
    ) {
      ElMessage.success(response.data);
    }
    hideLoading();
    return response;
  },
  error => {
    // The request was made and the server responded with a status code
    if (error.response) {
      console.log("error", error.response);
      switch (error.response.status) {
        case 404:
          ElMessage.error(
            `Error code 404:资源不存在-------${error.response.data}`
          );
          break;
        case 403:
          ElMessage.error(
            `Error code 403：未授权-----您当前的账户:[${store.state.username}]无权限使用此功能，请联系管理员管理该账户权限`
          );
          break;
        case 401:
          ElMessageBox.confirm(
            "Error code 401：未登录或凭证已过期，点击返回登录页面",
            "提示",
            {
              confirmButtonText: "返回登录页",
              cancelButtonText: "取消"
            }
          ).then(() => {
            router.push({ name: "login" });
          });
          break;
        case 400: {
          ElMessage.error(`Error code 400----${error.response.data}`);
          break;
        }
        case 500: {
          ElMessage.error(`服务器内部错误-------${error.response.data}`);
        }
      }
      hideLoading();
      return Promise.reject(error.response);
    }
  }
);

export default Request;
